import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import promptAction from '@ohos.promptAction';
import window from '@ohos.window';
import { CommonConstant as Const } from '../common/Constant';
import { BusinessError } from '@ohos.base';
import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider';
import common from '@ohos.app.ability.common'
import { KvStoreModel } from '../model/KvStoreModel'
let kvStoreModel: KvStoreModel = new KvStoreModel()

import dataPreferences from '@ohos.data.preferences';

export let SettingPreferences: dataPreferences.Preferences | null = null;

const MSG_SEND_METHOD: string = 'funA'

// key不重复写入
export function SettingSet(key:string,value:string){
  if(SettingPreferences!=undefined)
  {
    if (SettingPreferences.hasSync(key)) {
      console.info("The key "+key+" is contained.");
      return
    } else {
      console.info("The key "+key+" does not contain.");
      // 此处以此键值对不存在时写入数据为例
      SettingPreferences.putSync(key, value);
      SettingPreferences.flush((err: BusinessError) => {
        if (err) {
          console.error(`The key Failed to flush. Code:${err.code}, message:${err.message}`);
          return;
        }
        console.info('The key Succeeded in flushing.');
      })
    }
  }
}

//只在有key时修改
export function SettingChange(key:string,value:string){
  if(SettingPreferences!=undefined)
  {
    if (SettingPreferences.hasSync(key)) {
      console.info("The key "+key+" is contained.");
      // 此处以此键值对不存在时写入数据为例
      SettingPreferences.putSync(key, value);
      SettingPreferences.flush((err: BusinessError) => {
        if (err) {
          console.error(`The key Failed to flush. Code:${err.code}, message:${err.message}`);
          return;
        }
        console.info('The key Succeeded in flushing.');
      })
    }else{
      console.info("The key "+key+" is NOT contained.");
    }

  }
}


// 在收到call事件后会触发callee监听的方法
function FunACall(data) {

  let bike_power = '';
  let bike_location = '';
  let max_duration = '';
  let  bike_duration = '';
  let  bike_distance = '';

  kvStoreModel.get(Const.PILOT_POWER_KEY,(value)=>
  {
    bike_power = value
  })
  kvStoreModel.get(Const.PILOT_LOCATION_KEY,(value)=>
  {
    bike_location = value
  })
  kvStoreModel.get(Const.PILOT_MAX_DURATION_KEY,(value)=>
  {
    max_duration = value
    // 使用电量预估续航,公式: 剩余电量/总电量 = 预计续航/用户设定最大续航
    bike_duration = (parseInt(max_duration)*parseInt(bike_power)/100).toFixed(0)
    // 累计骑行 = 最大续航-预计续航
    bike_distance = (parseInt(max_duration) - parseInt(bike_duration)).toFixed(0)
    promptAction.showToast({'message':'获得骑行数据:'+bike_duration+bike_distance})
  })

  // 获取call事件中传递的所有参数
  let params = JSON.parse(data.readString())
  if (params.formId !== undefined) {
    let curFormId = params.formId;
    let message = params.detail;
    console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
    let formData = {
      'power': bike_power, // 和卡片布局中-电量对应
      'location': bike_location, // 和卡片布局中-位置对应
      'distance': bike_distance, // 和卡片布局中-里程对应
      'duration': bike_duration, // 和卡片布局中-预计续航对应
      'beep': '找车中.', // 和卡片布局中-响铃找车对应
      'lock': '正在开锁', // 和卡片布局中-开锁对应
    };
    let formMsg = formBindingData.createFormBindingData(formData)
    formProvider.updateForm(curFormId, formMsg).then((data) => {
      console.info('updateForm success.' + JSON.stringify(data));
    }).catch((error) => {
      console.error('updateForm failed:' + JSON.stringify(error));
    })
  }
  return null;
}


export default class EntryAbility extends UIAbility {

  onCreate(want, launchParam) {
    globalThis.context  = this.context
    kvStoreModel.createKvStore(globalThis.context,(value)=>{
      console.info('KVStore:kvStoreModel.createKvStore Callback'+value)
    })

    // 如果UIAbility第一次启动，call事件后会触发onCreate生命周期回调
    console.info('Want:' + JSON.stringify(want));
    try {
       // 监听call事件所需的方法
      this.callee.on(MSG_SEND_METHOD, FunACall);
    } catch (error) {
      console.log(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
    }
  }

  onDestroy() {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage) {
    // Main window is created, set main page for this ability
    let options: dataPreferences.Options = { name: 'myStore' };
    SettingPreferences = dataPreferences.getPreferencesSync(this.context, options);
    /**
     * 设 置
     */
    SettingSet('ALLPOWER','1519')
    SettingSet('Duration','999')
    SettingSet('Distance','520')
    SettingSet('BikeIP','192.168.56.101') // 设置值，如果有了就不需要设定默认值了
    AppStorage.setOrCreate('ALLPOWER', SettingPreferences.getSync('ALLPOWER','1519'));
    AppStorage.setOrCreate('Duration', SettingPreferences.getSync('Duration','999'));
    AppStorage.setOrCreate('Distance', SettingPreferences.getSync('Distance','520'));
    AppStorage.setOrCreate('BikeIP', SettingPreferences.getSync('BikeIP','192.168.56.101'));
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    try {
      dataPreferences.getPreferences(this.context, 'PilotStore', (err, preferences) => {
        if (err) {
          console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
          return;
        }
        console.info('Succeeded in getting preferences.');
        // 请确保获取到Preferences实例后，再进行相关数据操作
      })
    } catch (err) {
      console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
    }

    windowStage.loadContent('pages/Index', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

  onWindowStageDestroy() {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground() {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground() {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}
